package com.magist.manage.web.service.impl;

import com.magist.core.constants.Deleted;
import com.magist.core.exception.BusinessException;
import com.magist.core.service.SimpleServiceImpl;
import com.magist.manage.web.dao.SysMenuMapper;
import com.magist.manage.web.dto.SysMenuDto;
import com.magist.manage.web.entity.SysMenu;
import com.magist.manage.web.service.SysMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysMenuServiceImpl extends SimpleServiceImpl<SysMenu> implements SysMenuService{

	@Autowired
	private SysMenuMapper sysMenuMapper;

	@Override
	public List<SysMenuDto> getTreeJson(SysMenu sysMenu) {
		Assert.hasLength(sysMenu.getParentId(),"菜单不存在");
		return this.getChild(sysMenu.getParentId());
	}

	private List<SysMenuDto> getChild(String parentId){
		SysMenu param = new SysMenu();
		param.setParentId(parentId);
		List<SysMenuDto> resultMenu = new ArrayList<>();
		List<SysMenu> childMenu = this.find(param);
		for(SysMenu c:childMenu) {
			SysMenuDto sysMenuDto = new SysMenuDto();
			BeanUtils.copyProperties(c, sysMenuDto);

			sysMenuDto.setChildren(this.getChild(c.getId()));
			resultMenu.add(sysMenuDto);
		}
		return resultMenu;
	}

	@Override
	public void delMenu(SysMenu sysMenu) {

		if(sysMenu.getLevel()==0){
			SysMenu param = new SysMenu();
			param.setParentId(sysMenu.getId());
			List<SysMenu> list = this.find(param);
			for(SysMenu ss:list){
				this.delete(ss);
			}
		}
		this.delete(sysMenu);
	}

	@Override
	public void addMenu(SysMenu sysMenu) {
		Assert.hasLength(sysMenu.getRouterName(),"前端路由名称为空");
		SysMenu param = new SysMenu();
		param.setRouterName(sysMenu.getRouterName());
		param.setDeleted(Deleted.NO_STR);
		if(this.find(param).size()>0){
			throw new BusinessException("菜单前端路由名称重复");
		}
		this.insert(sysMenu);
	}

	@Override
	public List<SysMenu> findByParentId(String parentId) {
		if(StringUtils.isEmpty(parentId)) {
			return null;
		}
		SysMenu sysMenu = new SysMenu();
		sysMenu.setParentId(parentId);
		return this.find(sysMenu);
	}
}